package com.ruoyi.file.utils;

import com.itextpdf.text.Font;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author william.zhao
 * @version 1.0
 * @date 2024/06/07/ 17:19
 * @since jdk-17.0.2
 */
public class CscpExcelToPdfUtils {

    /**
     * @param sourcePath 源文件地址 如 D:\\1.xlsx
     * @param targetPath 目标文件地址 如 D:\\1.pdf
     */
    @SneakyThrows
    public static void excelToPdf(String sourcePath, String targetPath) {
        try (Workbook workbook = WorkbookFactory.create(new File(sourcePath));
             FileOutputStream fos = new FileOutputStream(targetPath)) {
            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            // 创建PDF文档对象
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);

            // 创建PDF输出流
            PdfWriter writer = PdfWriter.getInstance(document, fos);

            // 打开PDF文档
            document.open();

            // 创建PDF表格对象
            PdfPTable table = new PdfPTable(sheet.getRow(0).getLastCellNum());

            // 设置表格宽度
            table.setWidthPercentage(100);

            // 设置表格标题，Example Table为表格标题
            // Paragraph title = new Paragraph("Example Table", new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 16, Font.BOLD));
            // title.setAlignment(Element.ALIGN_CENTER);
            //  document.add(title);

            // 添加表格内容
            for (Row row : sheet) {
                for (Cell cell : row) {
                    System.out.println(cell.getCellType() + ", " + cell.getCellStyle().getDataFormatString() +"," + cell.getCellStyle().getDataFormat());
                    PdfPCell pdfCell = null;
                    if (cell.getCellType().toString().equals("NUMERIC")) {
                        pdfCell = new PdfPCell(new Paragraph(cell.getDateCellValue() + "", new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12)));
                    } else {
                        pdfCell = new PdfPCell(new Paragraph(cell.getStringCellValue(), new Font(BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12)));
                    }

                    pdfCell.setBorderWidth(1f);
                    pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    table.addCell(pdfCell);
                }
            }

            // 添加表格到PDF文档
            document.add(table);

            // 关闭PDF文档
            document.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}
